package com.taotao.service.impl;


import com.taotao.common.pojo.EasyUIDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.EasyUITreeNode;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.service.ContentCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {

    @Autowired
    private  TbContentCategoryMapper  tbContentCategoryMapper;

        //查询所有的节点信息
    @Override
    public List<EasyUITreeNode> getContentCategoryList(Long parentId) throws Exception {
        TbContentCategoryExample example = new  TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbContentCategory> list = tbContentCategoryMapper.selectByExample(example);
        //5.转成EasyUITreeNode 列表
        List<EasyUITreeNode> nodes = new ArrayList<>();
        for (TbContentCategory tbContentCategory:list){
            EasyUITreeNode node = new EasyUITreeNode();
            node.setId(tbContentCategory.getId());
            node.setState(tbContentCategory.getIsParent()?"closed":"open");
            node.setText(tbContentCategory.getName());
            nodes.add(node);
        }

        return nodes;
    }




    //创建节点
    @Override
    public TaotaoResult createContentCategory(Long parentId, String name)throws Exception {
        TbContentCategory tbContentCategory = new TbContentCategory();
        tbContentCategory.setCreated(new Date());
        tbContentCategory.setIsParent(false);
        tbContentCategory.setName(name);
        tbContentCategory.setParentId(parentId);
        tbContentCategory.setSortOrder(1);
        tbContentCategory.setStatus(1);
        tbContentCategory.setUpdated(tbContentCategory.getCreated());
        //2.插入contentcategory表数据
        tbContentCategoryMapper.insert(tbContentCategory);
        //3.返回taotaoresult 包含内容分类的id   需要主键返回
        TbContentCategory parent = tbContentCategoryMapper.selectByPrimaryKey(parentId);
        if (parent.getIsParent()==false){
            parent.setIsParent(true);
            tbContentCategoryMapper.updateByPrimaryKeySelective(parent);
        }
        return TaotaoResult.ok(tbContentCategory);

    }

    //更新节点
    @Override
    public void updateContentCategory(Long id, String name)throws Exception {
        tbContentCategoryMapper.updateContentCategory(id,name);
    }
}
